<?php
/**
 * 财务管理
 */
namespace app\admin\controller;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\exception\ValidateException;
use app\admin\model\Member as MemberModel;
use app\admin\model\UserMoneyLog as UserMoneyLogModel;
use app\common\common;
use app\admin\model\MemberWithdrawal as MemberWithdrawalModel;
use app\admin\model\MemberTransfer as MemberTransferModel;
use app\admin\model\MemberTransaction as MemberTransactionModel;
use think\facade\Db;
use app\api\model\BaseConfig as BaseConfigModel;

class Finance extends Admin
{
    /**
     * 资金流水记录
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function capital_list(){
        if (!$this->request->isPost()){
            //操作类型
            $capital_config = config('capital');
            $capital = [];
            foreach ($capital_config as $k => $v){
                $capital[] = ['id'=>$k,'name'=>$v['simplified']];
            }

            return view('capital_list',['capital'=>json_encode($capital)]);
        }else{
            $limit  = $this->request->post('limit', 20, 'intval');
            $page = $this->request->post('page', 1, 'intval');
            $order  = $this->request->post('order', '', 'serach_in');	//排序字段
            $sort  = $this->request->post('sort', '', 'serach_in');		//排序方式

            $where['mid']  = $this->request->post('mid', '', 'serach_in');
            if(!is_numeric($where['mid'])){
                $member = MemberModel::address($where['mid']);
                if(!empty($member)){
                    $member = $member->toArray();
                    $where['mid'] = $member['id'];
                }
            }
            //币种
            $currency = $this->request->post('currency', 0, 'intval');
            if($currency!=0) $where['currency'] = common::key_currency($currency);
            //来源
            $where['type'] = $this->request->post('type', '', 'serach_in');
            // 1:增加 2:减少
            $where['status'] = $this->request->post('status', 0, 'intval');
            if($where['status'] == 0) unset($where['status']);

            $orderby = ($sort && $order) ? $sort.' '.$order : 'id desc';
            //获取用户等级列表
            $res = UserMoneyLogModel::getList(formatWhere($where),$page,$limit,$orderby);
            foreach ($res['data'] as $k => $v){
                $res['data'][$k]['username'] = $v['mid'].' | '.$v['username'];
            }

            $data['status'] = 200;
            $data['data'] = $res;
            return json($data);
        }
    }

    /**
     * 提现列表
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function withdrawal_list(){
        if (!$this->request->isPost()){
            $address['usdt_address'] = BaseconfigModel::config_data('usdt_address');
            $address['usdt_contract'] = BaseconfigModel::config_data('usdt_contract');

            return view('withdrawal_list',['usdt_info'=>$address]);
        }else{
            $limit  = $this->request->post('limit', 20, 'intval');
            $page = $this->request->post('page', 1, 'intval');
            $order  = $this->request->post('order', '', 'serach_in');	//排序字段
            $sort  = $this->request->post('sort', '', 'serach_in');		//排序方式

            $orderby = ($sort && $order) ? $sort.' '.$order : 'id desc';

            $where['mid']  = $this->request->post('mid', '', 'serach_in');
            if(!is_numeric($where['mid']) && !empty($where['mid'])){
                $member = MemberModel::address($where['mid']);
                if(!empty($member)){
                    $member = $member->toArray();
                    $where['mid'] = $member['id'];
                }
            }

            //币种
            $currency = $this->request->post('currency', 0, 'intval');
            if($currency!=0) $where['currency'] = common::key_currency($currency);

            $res = MemberWithdrawalModel::getList(formatWhere($where),$page,$limit,$orderby);

            foreach ($res['data'] as $k => $v){
                //查询用户名
                $member = MemberModel::getDetails($v['mid']);
                $res['data'][$k]['username'] = !empty($member) ? $v['mid'].' | '.$member['username'] : $v['mid'];
            }

            $data['status'] = 200;
            $data['data'] = $res;
            return json($data);

        }
    }

    /**
     * 交易列表
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function transaction_list(){
        if (!$this->request->isPost()){
            return view('transaction_list');
        }else {
            $limit = $this->request->post('limit', 20, 'intval');
            $page = $this->request->post('page', 1, 'intval');
            $order = $this->request->post('order', '', 'serach_in');    //排序字段
            $sort = $this->request->post('sort', '', 'serach_in');        //排序方式

            $orderby = ($sort && $order) ? $sort.' '.$order : 'id desc';

            $where['mid'] = $this->request->post('mid', '', 'serach_in');
            if(!is_numeric($where['mid'])){
                $member = MemberModel::address($where['mid']);
                if(!empty($member)){
                    $member = $member->toArray();
                    $where['mid'] = $member['id'];
                }
            }

            //币种
            $currency = $this->request->post('currency', 0, 'intval');
            if ($currency != 0) $where['currency'] = common::key_currency($currency);

            $res = MemberTransactionModel::getList(formatWhere($where),$page,$limit,$orderby);

            foreach ($res['data'] as $k => $v){
                //查询用户名
                $member = MemberModel::getDetails($v['mid']);
                $res['data'][$k]['username'] = !empty($member) ? $v['mid'].' | '.$member['username'] : $v['mid'];
                $res['data'][$k]['receive_username'] = $v['receive_mid']." | ".$v['address'];
            }

            $data['status'] = 200;
            $data['data'] = $res;
            return json($data);
        }
    }

    /**
     * 提现失败
     * @return \think\response\Json|\think\response\View
     */
    function withdrawal_fail(){
        if (!$this->request->isPost()){
            return view('withdrawal_fail');
        }else{
            $data = $this->request->only(explode(',','id,remarks'),'post',null);
            if(empty($data['id'])) throw new ValidateException ('参数错误');

            Db::startTrans();
            try{
                MemberWithdrawalModel::examine($data['id'],3,$data['remarks']);
                // 提交事务
                Db::commit();
                return json(['status'=>200,'msg'=>'操作成功']);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                throw new ValidateException ('参数错误');
            }
        }
    }

    /**
     * 提现通过
     * @return \think\response\Json|\think\response\View
     */
    function withdrawal_adopt(){
        $id  = $this->request->post('id', '', 'intval');
        Db::startTrans();
        try{
            MemberWithdrawalModel::examine($id,2);
            // 提交事务
            Db::commit();
            return json(['status'=>200,'msg'=>'操作成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new ValidateException ('参数错误');
        }

    }

    /**
     * 转账列表
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function transfer_list(){
        if (!$this->request->isPost()){
            return view('transfer_list');
        }else {
            $limit = $this->request->post('limit', 20, 'intval');
            $page = $this->request->post('page', 1, 'intval');
            $order = $this->request->post('order', '', 'serach_in');    //排序字段
            $sort = $this->request->post('sort', '', 'serach_in');        //排序方式

            $orderby = ($sort && $order) ? $sort.' '.$order : 'id desc';

            //发起转账用户
            $where['mid|receive_mid'] = $this->request->post('mid', '', 'serach_in');
            if(!is_numeric($where['mid|receive_mid'])){
                $member = MemberModel::address($where['mid|receive_mid']);
                if(!empty($member)){
                    $member = $member->toArray();
                    $where['mid|receive_mid'] = $member['id'];
                }
            }

            //币种
            $currency = $this->request->post('currency', 0, 'intval');
            if ($currency != 0) $where['currency'] = common::key_currency($currency);

            $res = MemberTransferModel::getList(formatWhere($where),$page,$limit,$orderby);

            foreach ($res['data'] as $k => $v){
                //查询用户名
                $member = MemberModel::getDetails($v['mid']);
                $res['data'][$k]['username'] = !empty($member) ? $v['mid'].' | '.$member['username'] : $v['mid'];
                $res['data'][$k]['receive_username'] = $v['receive_mid']." | ".$v['address'];
            }

            $data['status'] = 200;
            $data['data'] = $res;
            return json($data);
        }
    }

    /**
     * 导出资金流水
     * @return \think\response\Json|void
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function dumpdata_capital(){
        $page = $this->request->param('page', 1, 'intval');
        $limit = config('my.dumpsize') ? config('my.dumpsize') : 1000;
        $state = $this->request->param('state');

        $order  = $this->request->post('order', '', 'serach_in');	//排序字段
        $sort  = $this->request->post('sort', '', 'serach_in');		//排序方式

        $where['mid']  = $this->request->post('mid', '', 'serach_in');
        //币种
        $currency = $this->request->post('currency', 0, 'intval');
        if($currency!=0) $where['currency'] = common::key_currency($currency);
        //来源
        $where['type'] = $this->request->post('type', '', 'serach_in');
        // 1:增加 2:减少
        $where['status'] = $this->request->post('status', 0, 'intval');
        if($where['status'] == 0) unset($where['status']);

        $orderby = ($sort && $order) ? $sort.' '.$order : 'id desc';
        //获取用户等级列表
        $res = UserMoneyLogModel::getList(formatWhere($where),$page,$limit,$orderby);
        foreach ($res['data'] as $k => $v){
            $res['data'][$k]['username'] = $v['mid'].' | '.MemberModel::getDetails($v['mid'])['username'];
        }

        $cache_key = 'Capital';
        if($page == 1){
            cache($cache_key,null);
            cache($cache_key,[]);
        }
        if($res['data']){
            cache($cache_key,array_merge(cache($cache_key),$res['data']));
            $data['percentage'] = ceil($page * 100/ceil($res['total']/$limit));
            $data['state'] =  'ok';
            return json($data);
        }
        if($state == 'ok'){
            $spreadsheet = new Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();

            $sheet->setCellValue('A1','编号');
            $sheet->setCellValue('B1','用户名');
            $sheet->setCellValue('C1','币种');
            $sheet->setCellValue('D1','更新数量');
            $sheet->setCellValue('E1','更新前');
            $sheet->setCellValue('F1','更新后');
            $sheet->setCellValue('G1','操作类型');
            $sheet->setCellValue('H1','注释');
            $sheet->setCellValue('I1','时间');

            foreach(cache($cache_key) as $k=>$v){
                $sheet->setCellValue('A'.($k+2),$v['id']);
                $sheet->setCellValue('B'.($k+2),$v['username']);
                $sheet->setCellValue('C'.($k+2),$v['currency']);
                $sheet->setCellValue('D'.($k+2),$v['num']);
                $sheet->setCellValue('E'.($k+2),$v['before_num']);
                $sheet->setCellValue('F'.($k+2),$v['after_num']);
                $sheet->setCellValue('G'.($k+2),$v['type_name']);
                $sheet->setCellValue('H'.($k+2),$v['remarks']);
                $sheet->setCellValue('I'.($k+2),date('Y-m-d H:i:s',$v['add_time']));
            }

            $filename = '资金流水.'.config('my.dump_extension');
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename='.$filename);
            header('Cache-Control: max-age=0');
            $writer = new Xlsx($spreadsheet);
            $writer->save('php://output');exit;
        }
    }

    /**
     * 提现导出
     * @return \think\response\Json|void
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function dumpdata_withdrawal(){
        $page = $this->request->param('page', 1, 'intval');
        $limit = config('my.dumpsize') ? config('my.dumpsize') : 1000;

        $state = $this->request->param('state');

        $order  = $this->request->post('order', '', 'serach_in');	//排序字段
        $sort  = $this->request->post('sort', '', 'serach_in');		//排序方式

        $orderby = ($sort && $order) ? $sort.' '.$order : 'id desc';

        $where['mid']  = $this->request->post('mid', '', 'serach_in');
        //币种
        $currency = $this->request->post('currency', 0, 'intval');
        if($currency!=0) $where['currency'] = common::key_currency($currency);

        $res = MemberWithdrawalModel::getList(formatWhere($where),$page,$limit,$orderby);

        foreach ($res['data'] as $k => $v){
            //查询用户名
            $member = MemberModel::getDetails($v['mid']);
            $res['data'][$k]['username'] = !empty($member) ? $v['mid'].' | '.$member['username'] : $v['mid'];

            switch ($v['status']) {
                case 1:
                    $res['data'][$k]['status'] = '申请中';
                    break;
                case 2:
                    $res['data'][$k]['status'] = '提现通过';
                    break;
                case 3:
                    $res['data'][$k]['status'] = '提现失败';
                    break;
            }
        }

        $cache_key = 'withdrawal';
        if($page == 1){
            cache($cache_key,null);
            cache($cache_key,[]);
        }
        if($res['data']){
            cache($cache_key,array_merge(cache($cache_key),$res['data']));
            $data['percentage'] = ceil($page * 100/ceil($res['total']/$limit));
            $data['state'] =  'ok';
            return json($data);
        }
        if($state == 'ok'){
            $spreadsheet = new Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();

            $sheet->setCellValue('A1','编号');
            $sheet->setCellValue('B1','用户名');
            $sheet->setCellValue('C1','收款用户');
            $sheet->setCellValue('D1','币种');
            $sheet->setCellValue('E1','提现数量');
            $sheet->setCellValue('F1','手续费');
            $sheet->setCellValue('G1','状态');
            $sheet->setCellValue('H1','发起时间');
            $sheet->setCellValue('I1','更新时间');

            foreach(cache($cache_key) as $k=>$v){
                $sheet->setCellValue('A'.($k+2),$v['id']);
                $sheet->setCellValue('B'.($k+2),$v['username']);
                $sheet->setCellValue('C'.($k+2),$v['address']);
                $sheet->setCellValue('D'.($k+2),$v['currency']);
                $sheet->setCellValue('E'.($k+2),$v['money']);
                $sheet->setCellValue('F'.($k+2),$v['charge_money']);
                $sheet->setCellValue('G'.($k+2),$v['status']);
                $sheet->setCellValue('H'.($k+2),$v['add_time']);
                $sheet->setCellValue('I'.($k+2),$v['update_time']);
            }

            $filename = '资金提现.'.config('my.dump_extension');
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename='.$filename);
            header('Cache-Control: max-age=0');
            $writer = new Xlsx($spreadsheet);
            $writer->save('php://output');exit;
        }
    }

    /**
     * 转账导出
     * @return \think\response\Json|void
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function dumpdata_transfer(){
        $page = $this->request->param('page', 1, 'intval');
        $limit = config('my.dumpsize') ? config('my.dumpsize') : 1000;

        $state = $this->request->param('state');

        $order = $this->request->post('order', '', 'serach_in');    //排序字段
        $sort = $this->request->post('sort', '', 'serach_in');        //排序方式

        $orderby = ($sort && $order) ? $sort.' '.$order : 'id desc';

        //发起转账用户
        $where['mid|receive_mid'] = $this->request->post('mid', '', 'serach_in');
        //币种
        $currency = $this->request->post('currency', 0, 'intval');
        if ($currency != 0) $where['currency'] = common::key_currency($currency);

        $res = MemberTransferModel::getList(formatWhere($where),$page,$limit,$orderby);

        foreach ($res['data'] as $k => $v){
            //查询用户名
            $member = MemberModel::getDetails($v['mid']);
            $res['data'][$k]['username'] = !empty($member) ? $v['mid'].' | '.$member['username'] : $v['mid'];
            $res['data'][$k]['receive_username'] = $v['receive_mid']." | ".$v['address'];
        }

        $cache_key = 'transfer';
        if($page == 1){
            cache($cache_key,null);
            cache($cache_key,[]);
        }
        if($res['data']){
            cache($cache_key,array_merge(cache($cache_key),$res['data']));
            $data['percentage'] = ceil($page * 100/ceil($res['total']/$limit));
            $data['state'] =  'ok';
            return json($data);
        }
        if($state == 'ok'){
            $spreadsheet = new Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();

            $sheet->setCellValue('A1','编号');
            $sheet->setCellValue('B1','发起用户');
            $sheet->setCellValue('C1','收款用户');
            $sheet->setCellValue('D1','币种');
            $sheet->setCellValue('E1','转账数量');
            $sheet->setCellValue('F1','手续费');
            $sheet->setCellValue('G1','备注');
            $sheet->setCellValue('H1','发起时间');

            foreach(cache($cache_key) as $k=>$v){
                $sheet->setCellValue('A'.($k+2),$v['id']);
                $sheet->setCellValue('B'.($k+2),$v['username']);
                $sheet->setCellValue('C'.($k+2),$v['receive_username']);
                $sheet->setCellValue('D'.($k+2),$v['currency']);
                $sheet->setCellValue('E'.($k+2),$v['money']);
                $sheet->setCellValue('F'.($k+2),$v['charge_money']);
                $sheet->setCellValue('G'.($k+2),$v['remarks']);
                $sheet->setCellValue('H'.($k+2),$v['add_time']);
            }

            $filename = '资金转账.'.config('my.dump_extension');
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename='.$filename);
            header('Cache-Control: max-age=0');
            $writer = new Xlsx($spreadsheet);
            $writer->save('php://output');exit;
        }
    }

}